import logging
import requests
from wxauto import WeChat

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 初始化微信客户端
wx = WeChat()

# DeepSeek API 配置
DEEPSEEK_API_KEY = "sk-9f5032eb91e942ee8b74219a6a8d9439"  # 你的 DeepSeek API 密钥
DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"

def get_deepseek_response(msg):
    """调用 DeepSeek API 获取回复"""
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",  # 使用的模型
        "messages": [{"role": "user", "content": msg}],  # 用户消息
        "temperature": 0.7  # 控制回复的随机性
    }
    try:
        response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()['choices'][0]['message']['content']  # 提取回复内容
    except Exception as e:
        logging.error(f"API 调用失败: {str(e)}")
        return "抱歉，我现在无法处理这个消息。"  # 失败时返回默认回复

# 主循环
while True:
    msgs = wx.GetAllNewMessage()  # 获取所有新消息
    if msgs:
        for sender, message_list in msgs.items():
            if sender == '肚笨猪':  # 跳过特定发送者
                logging.info(f"跳过来自 {sender} 的消息")
                continue

            for msg in message_list:
                # 提取消息内容（确保是纯文本）
                if hasattr(msg, 'content'):  # 检查消息是否有 content 属性
                    msg_content = msg.content
                else:
                    msg_content = str(msg)  # 如果无法提取，直接转换为字符串

                logging.info(f"收到来自 {sender} 的消息: {msg_content}")
                reply_content = get_deepseek_response(msg_content)  # 调用 DeepSeek API 获取回复
                wx.SendMsg(reply_content, sender)  # 发送回复
                logging.info(f"已回复 {sender}: {reply_content}")

                # 切换回文件传输助手，防止消息干扰
                wx.ChatWith(who='文件传输助手')
                break  # 每次只处理第一条消息
            break  # 每次只处理一个聊天
    else:
        wx.ChatWith(who='文件传输助手')  # 没有新消息时切换到文件传输助手